<template>
  <div>
    <el-row class="page_top">
      <el-col :span="6">
        <el-form :model="search">
          <el-form-item prop="ips_name">
            <el-autocomplete
              :fetch-suggestions="querySearchAsync"
              placeholder="请输入资源名称"
              @select="handleSelect"
              v-model="search.ips_name"
              clearable
              @clear="cleanSearch"
              ref="elautocomplete"
            >
              <template slot-scope="{ item }">
                <span>{{ item.label }}</span>
                <span v-show="false">{{ item.value }}</span>
              </template>
              <template slot="append">
                <el-button slot="append" icon="el-icon-search" @click="searchAll"></el-button>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="18">
        <el-button type="primary" size="small" @click="add" class="btn_add">添加</el-button>
      </el-col>
    </el-row>

    <el-table :data="lists" border style="width: 100%">
      <el-table-column type="index" width="50" align="center" label="序号"></el-table-column>
      <el-table-column label="资源名称" width="150" align="center" prop="ips_name"></el-table-column>
      <el-table-column label="资源池URL" prop="SERVER_URL"></el-table-column>
      <!-- 操作列 -->
      <el-table-column label="管理" fixed="right" align="center" width="150">
        <template slot-scope="props">
          <!-- 修改 -->
          <el-button size="mini" @click="edit(props.row)">修改</el-button>
          <!-- 删除 -->
          <el-button type="danger" size="mini" @click="del(props.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="table-pageblock">
      <!-- current-page 当前页数  page-size 每页显示数 total 总页数-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10,20,30,40,50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <!-- 弹窗 新增or修改 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogShow" fullscreen>
      <!-- 添加/修改表单 -->
      <el-form label-width="100px" ref="logos" :model="logos">
        <el-row>
          <el-col :span="12">
            <el-form-item label="资源名称" prop="ips_name">
              <el-input v-model="logos.ips_name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资源池URL" prop="SERVER_URL">
              <el-input v-model="logos.SERVER_URL"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button type="primary" size="small" v-if="dialogTitle === '添加'" @click="create">添加</el-button>
        <el-button size="small" v-else @click="update">修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { post } from "../../http/index";
import moment from "moment";
export default {
  name: "ips",
  data() {
    return {
      // 初始数据
      lists: [],

      // 查询条件
      search: {
        ips_name: ""
      },

      // 远程搜索
      restaurants: [],
      // 计时器
      timeout: null,

      // 当前页
      currentPage: 1,
      // 当前数
      pageSize: 10,
      // 总条目数
      total: 20,

      // 弹窗标题
      dialogTitle: "",
      // 弹窗是否显示
      dialogShow: false,

      logos: {
        ips_name: "",
        SERVER_URL: ""
      }
    };
  },
  filters: {
    filterTime: value => {
      return moment(value).format("YYYY-MM-DD");
    }
  },
  // 加载实例后执行
  mounted() {
    this.getLogos();
    this.loadAll();
  },

  methods: {
    loadAll() {
      let list = [];
      let params = {
        mark: 1
      };
      post('/api/ips/getIpsAll', params).then(res => {
        if (res.success) {
          for (let i = res.data.length; i--; ) {
            list.push({
              value: res.data[i].ips_name,
              label: res.data[i].ips_name
            });
          }
          this.restaurants = list;
        } else {
          this.$message({
            message: res.message,
            type: "error"
          });
        }
      }).catch(err => {
        console.log(err);
      });
    },

    querySearchAsync(queryString, cb) {
      let _this = this;
      let restaurants = _this.restaurants;
      let results = queryString ? _this.createStateFilter(queryString) : restaurants;
      clearTimeout(_this.timeout);
      _this.timeout = setTimeout(() => {
        cb(results);
      }, 200 * Math.random());
    },

    createStateFilter(queryString) {
      let _this = this;
      // 匹配结果
      let restaurants = _this.restaurants;
      // 输入值转换大写
      queryString = queryString.toUpperCase();
      let result = restaurants.filter(
        state => state.value.toUpperCase().indexOf(queryString) === 0
      );
      return result;
    },

    handleSelect(item) {
      let _this = this;
      _this.$nextTick(() => {
        _this.search.ips_name = item.label;
      });
    },

    cleanSearch() {
      let _this = this;
      _this.$nextTick(() => {
        _this.search.ips_name = "";
      });
    },

    // 根据选择条件查询
    searchAll() {
      let _this = this;
      let params = {
        ips_name: _this.search.ips_name === undefined || null ? "" : _this.search.ips_name,
        mark: 1,
        limit: _this.pageSize,
        offset: _this.currentPage
      };
      post('/api/ips/getIpslist', params).then(res => {
        if (res.success) {
          _this.lists = res.data.rows;
          _this.total = res.data.count;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!res.data.rows.length && _this.currentPage !== 1) {
            // 当前页减一
            _this.currentPage -= 1;
            // 调用自己
            _this.getLogos();
          }
        } else {
          this.$message({
            message: res.message,
            type: "error"
          });
        }
      }).catch(err => {
        console.log(err);
      });
    },

    // 查询登录账户
    getLogos() {
      let _this = this;
      let params = {
        ips_name: _this.search.ips_name === undefined || null ? "" : _this.search.ips_name,
        mark: 1,
        limit: _this.pageSize,
        offset: _this.currentPage
      };
      post('/api/ips/getIpslist', params).then(res => {
        if (res.success) {
          _this.lists = res.data.rows;
          _this.total = res.data.count;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!res.data.rows.length && _this.currentPage !== 1) {
            // 当前页减一
            _this.currentPage -= 1;
            // 调用自己
            _this.getLogos();
          }
        } else {
          this.$message({
            message: res.message,
            type: "error"
          });
        }
      }).catch(err => {
        console.log(err);
      });
    },

    // 每页显示的条数改变
    handleSizeChange(val) {
      this.pageSize = val;
      // 调用刷新页面
      this.getLogos();
    },

    // 当前页码
    handleCurrentChange(val) {
      this.currentPage = val;
      // 调用
      this.getLogos();
    },

    // 显示编辑界面
    edit(row) {
      let _this = this;
      _this.dialogTitle = "修改";
      _this.dialogShow = true;
      let info = row;
      _this.logos = Object.assign({}, info);
    },

    // 显示新增界面
    add() {
      let _this = this;
      _this.dialogTitle = "添加";
      _this.dialogShow = true;
      _this.logos = {
        ips_name: "",
        SERVER_URL: ""
      };
    },

    // 新增
    create() {
      let _this = this;
      const logbox = this.$refs["logos"];
      this.$nextTick(() => {
        logbox.validate(valid => {
          if (valid) {
            let params = {
              ips_name: _this.logos.ips_name,
              SERVER_URL: _this.logos.SERVER_URL,
              mark: 0
            };
            post('/api/ips/addIps', params).then(res => {
              if (res.success) {
                this.$message({
                  message: res.message,
                  type: "success"
                });
                _this.dialogShow = false;
                _this.getLogos();
                _this.loadAll();
              } else {
                this.$message({
                  message: res.message,
                  type: "error"
                });
              }
            }).catch(err => {
              console.log(err);
            });
          } else {
            return false;
          }
        });
      });
    },

    // 修改
    update() {
      let _this = this;
      const logbox = this.$refs["logos"];
      this.$nextTick(() => {
        logbox.validate(valid => {
          if (valid) {
            let params = {
              id: _this.logos.id,
              ips_name: _this.logos.ips_name,
              SERVER_URL: _this.logos.SERVER_URL
            };
            post('/api/ips/updateIps', params).then(res => {
              if (res.success) {
                this.$message({
                  message: res.message,
                  type: "success"
                });
                _this.dialogShow = false;
                _this.getLogos();
                _this.loadAll();
              } else {
                this.$message({
                  message: res.message,
                  type: "error"
                });
              }
            }).catch(err => {
              console.log(err);
            });
          } else {
            return false;
          }
        });
      });
    },

    // 删除客户
    del(row) {
      let _this = this;
      let params = {
        id: row.id,
        mark: 1
      };
      // 删除二次确认
      _this.$confirm("确认删除选中的信息吗？", "提示", {
        type: "warning"
      }).then(() => {
        post('/api/ips/delIps', params).then(res => {
          if (res.success) {
            this.$message({
              message: "删除成功！",
              type: "success"
            });
            _this.getLogos();
            _this.loadAll();
          }
        }).catch(err => {
          console.log(err);
        });
      }).catch(() => {
        _this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
    }
  }
};
</script>

<style lang='scss'>
@import "./index.scss";
</style>
